<template>
  <div>
    <TodoToubu @addList="addList"></TodoToubu>
    <TodoZhuti
      :list="renderList"
      @changeFlag="changeFlag"
      @belBtn="belBtn"
      @changeAll="changeAll"
    ></TodoZhuti>
    <TodoWeibu
      @clearQchu="clearQchu"
      :isShow="isShow"
      :sum="sum"
      :type="type"
      @comporType="comporType"
    ></TodoWeibu>
  </div>
</template>

<script>
import TodoToubu from './components/TodoToubu.vue'
import TodoZhuti from './components/TodoZhuti.vue'
import TodoWeibu from './components/TodoWeibu.vue'

export default {
  components: {
    TodoToubu,
    TodoZhuti,
    TodoWeibu,
  },
  props: {},
  data() {
    return {
      list: JSON.parse(localStorage.getItem('todoList')) || [
        {
          flag: true,
          name: '唱跳',
          id: 1,
        },
        {
          flag: true,
          name: 'rap',
          id: 2,
        },
        {
          flag: false,
          name: '篮球',
          id: 3,
        },
      ],
      type: 'all',
    }
  },
  computed: {
    // 统计未完成的数量
    sum() {
      return this.list.filter((item) => !item.flag).length
    },
    isShow() {
      return this.list.some((item) => item.flag)
    },
    renderList() {
      switch (this.type) {
        case 'all':
          return this.list
        case 'active':
          return this.list.filter((item) => !item.flag)
        case 'completed':
          return this.list.filter((item) => item.flag)
        default:
          return this.list
      }
    },
  },
  //监听
  watch: {
    list: {
      immediate: true,
      deep: true,
      handler(newVal) {
        localStorage.setItem('todoList', JSON.stringify(newVal))
      },
    },
  },
  methods: {
    // 添加事件子组件按下回车父组件接收name，并且添加
    // 解构list数据
    addList(name) {
      this.list = [
        ...this.list,
        {
          flag: false, //默认显示未完成
          name: name,
          id: +new Date(), //new Date时间戳前面加个+号，把事件戳转换为数字类型
        },
      ]
    },
    // 修改事件完成状态，显示为true可以进行清除已完成
    changeFlag(id, flag) {
      this.list.forEach((item) => {
        if (item.id === id) item.flag = flag
      })
    },
    // 删除事件
    // 筛选 过滤id
    belBtn(id) {
      this.list.filter((item) => item.id !== id)
    },
    // 清除已完成任务
    clearQchu() {
      this.list = this.list.filter((item) => !item.flag)
    },
    comporType(name) {
      this.type = name
    },
    // 点击全选全部选中
    changeAll(flag) {
      this.list.forEach((item) => (item.flag = flag))
    },
  },
}
</script>

<style scoped></style>
